package leetcode.Y2024M6.study;

import leetcode.Y2024M6.TreeNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class S102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> rootList = new ArrayList<>();
        rootList.add(root.val);
        res.add(rootList);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> nodeList = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                    nodeList.add(node.left.val);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    nodeList.add(node.right.val);
                }

                size--;
            }
            if (!nodeList.isEmpty())
                res.add(nodeList);
        }
        return res;
    }

    @Test
    public void test() {
        int[] root = {3, 9, 20, -1, -1, 15, 7};
        System.out.println(levelOrder(TreeNode.createTree(root)));
    }
}
